<template>
  <div class="search-container">
    <!-- 在 van-search 外层增加 form 标签，且 action 不为空，即可在 iOS 输入法中显示搜索按钮。 -->
    <form action="/">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
    </form>
    <!-- 缕清一下逻辑
    1,只有当搜索框里没有东西,又没有回车的时候,才显示历史记录
    2.只有在有字的时候才能显示提示组件
    3.回车后必须显示结果
     -->
    <search-result
      v-if="isResultShow"
      :search-text="searchText"
    ></search-result>
    <search-suggestion
      v-else-if="searchText"
      :search-text="searchText"
      @search="onSearch"
    ></search-suggestion>
    <search-history
      v-else
      :search-histories="searchHistories"
      @search="onSearch"
      @clear-search-histories="searchHistories = []"
    ></search-history>
  </div>
</template>

<script>
import searchHistory from './component/search-history'
import searchResult from './component/search-result'
import searchSuggestion from './component/search-suggestion'
import { setItem, getItem } from '@/utils/storage.js'
export default {
  name: 'SearchIndex',
  data () {
    return {
      searchText: '',
      isResultShow: false,
      searchHistories: getItem('TOUTIAO_SEARCH_HISTORY') || []
    }
  },
  components: {
    searchHistory,
    searchResult,
    searchSuggestion
  },
  watch: {
    searchHistories (value) {
      console.log(value)
      setItem('TOUTIAO_SEARCH_HISTORY', value)
    }
  },

  methods: {
    onSearch (val) {
      this.searchText = val
      // 把触发的数据 首先用indexOf 查找是否出现过,如果出现过,删掉过去的,重新追加到数组,最后传到子组件
      const index = this.searchHistories.indexOf(val)
      if (index !== -1) {
        this.searchHistories.splice(index, 1)
      }
      this.searchHistories.unshift(val)
      this.isResultShow = true
    },
    onCancel () {
      this.$router.back()
    }
  }
}
</script>

<style scoped lang="less">
.search-container {
  .van-search__action {
    color: #fff;
  }
}
</style>
